package net.zhengxinyun.performance.App.appCtrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.App.dto.DepartDTO;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.dto.SystemDTO;
import net.zhengxinyun.performance.App.dto.UserDTO;
import net.zhengxinyun.performance.App.dto.indexRight.IndexRightDTO;
import net.zhengxinyun.performance.App.service.UnionOtherSys.UnionOtherSysService;
import net.zhengxinyun.performance.Util.MD5;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.criteria.CriteriaService;
import net.zhengxinyun.performance.service.departClass.DepartClassItemService;
import net.zhengxinyun.performance.service.departClass.DepartClassService;
import net.zhengxinyun.performance.service.departClass.DepartHeadService;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.setTime.SetTimeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统设置
 */

@RestController
@RequestMapping("/app/sys")
public class SystemCtrl extends BaseCtrl {

    @Autowired
    private CriteriaService criteriaService;
    @Autowired
    private DepartClassService departClassService;

    @Autowired
    private DepartmentService deptmentService;

    @Autowired
    private UserService userService;


    @Autowired
    private SetTimeService setTimeService;

    @Autowired
    private TownIndicatorsService townIndicatorsService;

    @Autowired
    private CountryIndicatorsService cityIndexService;

    @Autowired
    private CountryUnitIndicatorsService departIndexSercice;
    @Autowired
    private RolePerService rolePerService;


    @Autowired
    private DepartClassService dpclassService;


    @Autowired
    private DepartClassItemService itemService;

    @Autowired
    private DepartHeadService headService;

    @Autowired
    private UnionOtherSysService unionService;


    @PostMapping("/manage")
    public Result<HashMap<String, Object>> systemManage(@RequestBody SystemDTO dto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", null);
        String currentYear = getCurrentYear();
        List<SystemDTO> sysdtos = new ArrayList<>();
        UserFilter userInfo = getUserInfo(dto.getUserPhone());
        ;
        switch (dto.getFuncCode()) {
            case "0": // 单位分类
                DepartClassFilter departClassFilter = new DepartClassFilter();
                //departClassFilter.setDatetime(currentYear);
                List<DepartClassFilter> query = departClassService.query(departClassFilter);
                for (DepartClassFilter item : query) {

                    sysdtos.add(new SystemDTO(item.getId(), item.getClassname(), "单位分类", "0"));
                }

                break;
            case "1": // 单位管理
                DepartmentFilter departmentFilter = new DepartmentFilter();
                if (!"admin".equals(userInfo.getUserPermissions())) {
                    departmentFilter.setDepartcode(userInfo.getDepartcode());
                }

                List<DepartmentFilter> depts = deptmentService.query(departmentFilter);
                for (DepartmentFilter item : depts) {

                    sysdtos.add(new SystemDTO(item.getId(), item.getDepartment(), "单位管理", "1", item));
                }
                break;
            case "2": //  用户管理
                UserFilter userFilter = new UserFilter();
                if (!"admin".equals(userInfo.getUserPermissions())) {
                    userFilter.setDepartcode(userInfo.getDepartcode());
                }

                List<UserFilter> userList = userService.queryUsers(userFilter);
                for (UserFilter item : userList) {
                    SystemDTO users = new SystemDTO(item.getId(), item.getUserName(), "用户管理", "2", item.getUserPhone(), item.getLoginTimes(), (item.getDel() + ""));
                    UserFilter insideInfo = new UserFilter();
                    BeanUtils.copyProperties(item,insideInfo);
                    users.setUserInfo(insideInfo);
                    sysdtos.add(users);

                }

                break;
            case "3": // 角色管理
                RolePerFilter roleFilter = new RolePerFilter();
                if (!"admin".equals(userInfo.getUserPermissions())) {
                    roleFilter.setDepartCode(userInfo.getDepartcode());
                }
                List<RolePerFilter> rolelist = rolePerService.query(roleFilter);
                for (RolePerFilter item : rolelist) {

                    sysdtos.add(new SystemDTO(item.getId(), item.getRole(), "角色管理", "3", item));

                }


                break;

            case "4"://自定义管理


        }
        map.put("data", sysdtos);
        System.out.println("-------接口：/manage");
        return ResultUtils.getSuccessResults(map);
    }

 /*   //获取所有分类
    @PostMapping("/deptclass")
    public Result<HashMap<String,Object>> deptClasses(@RequestBody DepartClassFilter classFilter)
    {
       //获取所有分类
        List<DepartClassFilter> query = departClassService.query(classFilter);

        HashMap<String,Object> map = new HashMap<>();
        map.put("data",query);

        return ResultUtils.getResults(Result.Status.SUCCESS, "获取县对乡镇指标数据成功", map);
    }*/

    // 单位管理
    @PostMapping("/editManage")
    public Result<HashMap<String,Object>> userManage(@RequestBody DepartmentFilter filter) {

       /* UserFilter userInfo = getUserInfo(filter.getUserPhone());
        if(!"admin".equals(userInfo.getUserPermissions()))
        {
            filter.setDepartcode(userInfo.getDepartcode());
        }
        List<DepartmentFilter> query = deptmentService.query(filter);
        dataMap.put("data",query);*/

        String optionType = filter.getOptionType();
        if (StringUtils.isBlank(optionType)) {
            return ResultUtils.getResults(Result.Status.ERROR, "optionType不能为空",null);
        }
        DepartmentEntity entiy = new DepartmentEntity();
        entiy.setDepartClas(filter.getDepartClas());
        entiy.setDepartAddr(filter.getDepartAddr());
        entiy.setDepartment(filter.getDepartment());
        entiy.setDepartType(filter.getDepartType());
        entiy.setDepartOldAddr(filter.getDepartOldAddr());
        entiy.setDepartOldName(filter.getDepartOldName());
        entiy.setDel(0);
        entiy.setRemark(filter.getRemark());
        entiy.setId(filter.getId());

        String opCode = "";
        switch (optionType) {
            case "add":

                opCode = deptmentService.insert(entiy);

                break;

            case "update":
                if (ObjectUtils.isBlank(entiy.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "id不能为空",null);
                }
                opCode = deptmentService.update(entiy);
                break;

            case "del":
                if (ObjectUtils.isBlank(entiy.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "id不能为空",null);
                }
                opCode = deptmentService.delete(entiy);
                break;
            case "query":
                DepartmentFilter departmentFilter = new DepartmentFilter();
                departmentFilter.setDepartType(filter.getDepartType());
                List<DepartmentFilter> listdepts = deptmentService.query(departmentFilter);
                HashMap<String,Object> maplist = new HashMap<>();
                maplist.put("data",listdepts);
                return  ResultUtils.getSuccessResults(maplist);


        }

        if (!opCode.contains("成功")) {
            return ResultUtils.getResults(Result.Status.ERROR, "操作失败",null);
        }


        return ResultUtils.getSuccessResults(null);
    }

    /**
     * //  用户管理 2020-01-20
     * 用户的增删改查
     **/
    @PostMapping("/editUser")
    public Result<HashMap<String, Object>> getdeptments(@RequestBody UserFilter filter) {

       /* UserFilter userInfo = getUserInfo(filter.getUserPhone());
        if(!"admin".equals(userInfo.getUserPermissions()))
        {
            filter.setDepartcode(userInfo.getDepartcode());
        }
        List<UserFilter> query = userService.query(filter);
        HashMap<String,Object> dataMap = new HashMap<>();*/
        /*  dataMap.put("data",query);*/

        String optionType = filter.getOptionType();
        if (StringUtils.isBlank(optionType)) {
            return ResultUtils.getResults(Result.Status.ERROR, "optionType不能为空", null);
        }


        UserEntity entity = new UserEntity();

        entity.setUserName(filter.getUserName());    //用户名
        entity.setUserPassword(filter.getUserPassword()); //密码
        entity.setDepartcode(filter.getDepartcode()); //单位编码
        entity.setUserPhone(filter.getUserPhone());//手机号
        entity.setNickName(filter.getNickName());//昵称
        entity.setUserPosition(filter.getUserPosition());//职务
        entity.setIsManger(filter.getIsManger());
        entity.setIsLeader(filter.getIsLeader());
        entity.setRoleRight(StringUtils.isBlank(filter.getRoleRight()) ? null : filter.getRoleRight().replace(", ", ","));//菜单
        entity.setBtnRight(StringUtils.isBlank(filter.getBtnRight()) ? null : filter.getBtnRight().replace(", ", ","));//菜单权限
        entity.setIndexRight(StringUtils.isBlank(filter.getIndexRight()) ? null : filter.getIndexRight().replace(", ", ","));//县对乡
        entity.setCityIndex(StringUtils.isBlank(filter.getCityIndex()) ? null : filter.getCityIndex().replace(", ", ","));//市指标
        entity.setDepartIndex(StringUtils.isBlank(filter.getDepartIndex()) ? null : filter.getDepartIndex().replace(", ", ","));//县直单位指标
        entity.setId(filter.getId());
        entity.setAppRole(appRoleValue(entity.getIsLeader(), entity.getDepartcode()));
        entity.setDel(filter.getDel());


        int code = 0;
        switch (optionType) {
            case "add":
                entity.setId(null);
                UserFilter tempfilter = new UserFilter();
                tempfilter.setUserName(filter.getUserName());
                List<UserFilter> query = userService.query(tempfilter);
                if(ObjectUtils.isNotBlank(query)){
                    return  ResultUtils.getResults(Result.Status.ERROR,"用户重复",null);
                }
                code = userService.insert(entity);
                break;
            case "update":
                if (ObjectUtils.isBlank(entity.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "用户id不能为空", null);
                }
                //取出旧密码：
                UserEntity userOld = userService.getUseInfo(entity.getId());
                if (userOld.getUserPassword().equals(entity.getUserPassword())) {
                    //密码一样不改变，密码不一样，说明修改了密码，重新加密
                    try {
                        entity.setUserPassword(MD5.md5(entity.getUserPassword(), MD5.MD5_STR));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                code = userService.updateByPrimaryKeySelective(entity);
                break;
            case "del":
                if (ObjectUtils.isBlank(entity.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "用户id不能为空", null);
                }
                code = userService.delete(entity);
                break;

            case "query":

                if (StringUtils.isBlank(filter.getKeyWord())) {
                    return ResultUtils.getResults("500", "keyWord关键字不能为空", null);

                }
                UserFilter userFilter = new UserFilter();

                //根据手机搜
                userFilter.setUserPhone(filter.getKeyWord());
                List<UserFilter> userFilterList1 = userService.queryUsers(userFilter);

                //根据单位关键字搜索
                userFilter.setUserPhone(null);
                userFilter.setDepartment(filter.getKeyWord());
                List<UserFilter> userFilterList2 = userService.queryUsers(userFilter);
                userFilterList1.addAll(userFilterList2);
                //根据昵称搜索
                userFilter.setDepartment(null);
                userFilter.setNickName(filter.getKeyWord());
                List<UserFilter> userFilterList3 = userService.queryUsers(userFilter);
                userFilterList1.addAll(userFilterList3);
                // 根据用户名搜索

                userFilter.setUserName(filter.getKeyWord());
                userFilter.setNickName(null);
                List<UserFilter> userFilterList4 = userService.queryUsers(userFilter);
                userFilterList1.addAll(userFilterList4);

                userFilterList1 = userFilterList1.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserFilter::getId))), ArrayList::new
                ));

                HashMap<String, Object> data = new HashMap<>();
                List<SystemDTO> sysdtos = new ArrayList<>();
                for (UserFilter item : userFilterList1) {
                    sysdtos.add(new SystemDTO(item.getId(), item.getUserName(), null, null, item.getUserPhone(), item.getLoginTimes(),(item.getDel()+"")));

                }

                data.put("data", sysdtos);

                return ResultUtils.getSuccessResults(data);


        }
        if (0 == code) {
            return ResultUtils.getResults(Result.Status.ERROR, "无数据更新", null);
        }
        return ResultUtils.getSuccessResults(null);
    }

    //app角色判断
    public String appRoleValue(int isleader, String departCode) {
        if (1 == isleader) {
            return "2";
        } else {
            //  String departcode = entity.getDepartcode();
            if (StringUtils.isBlank(departCode)) {
                return "0";
            }
            //判断乡镇或者县直单位
            DepartmentEntity departmentEntity = deptmentService.selectByCode(departCode);
            if (departmentEntity.getDepartType().equals("乡镇")) {
                return 3 + "";
            } else {
                return "4";
            }
        }

    }


    //    根据id获取用户的基本信息，包括菜单权限，按钮权限，市指标权限，县指标权限，单位指标权限
    @PostMapping("/getUserinfo")
    public Result<HashMap<String, Object>> getUserIndexRight(@RequestBody UserFilter filter) {

        String userPhone = filter.getUserPhone();
        UserFilter userFilter = new UserFilter();
        userFilter.setUserPhone(userPhone);

        Long userid = filter.getId();
        userFilter.setId(userid);//id传空的， 说明是点击了 添加用户的按钮
        List<UserFilter> userFilterList = userService.queryUsers(userFilter);
        if (ObjectUtils.isBlank(userFilterList)) {
            return ResultUtils.getResults(Result.Status.ERROR, "找不到该用户", null);
        }
        String currentYear = getCurrentYear();
        UserFilter currentUser = userFilterList.get(0);  // 当前选择的用户

        //另外获取登陆者权限：

        UserFilter loginFilter = new UserFilter();
        loginFilter.setUserPhone(filter.getLoginTel());
        List<UserFilter> sysAdmins = userService.queryUsers(loginFilter);
        UserFilter loginUser = sysAdmins.get(0);//当前登录的用户



        /*  县对乡镇指标 */
        System.out.println(currentYear);

        TownIndicatorsFilter townfilter = new TownIndicatorsFilter();
        CountryIndicatorsFilter cityfiler = new CountryIndicatorsFilter();
        CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();

        if (!"admin".equals(loginUser.getUserPermissions())) {
            if ("县直单位".equals(currentUser.getDepartType())) {
                townfilter.setLeadUnit(currentUser.getDepartcode());
            }
            cityfiler.setLeadUnit(currentUser.getDepartcode());
            departFilter.setLeadUnit(currentUser.getDepartcode());
        }

        townfilter.setIndexType("二级指标");
        townfilter.setDateTime(currentYear);
        List<TownIndicatorsFilter> listIndexs = townIndicatorsService.query(townfilter);
        //县对乡指标
        String townIndexs = currentUser.getIndexRight();
        List<String> haves = Util.strToList(townIndexs);
        List<IndexRightDTO> townrights = new ArrayList<>();
        for (TownIndicatorsFilter town : listIndexs) {

            List<String> haveds = haves.stream().filter(s -> s.equals(town.getId() + "")).collect(Collectors.toList());

            IndexRightDTO dto = new IndexRightDTO();
            dto.setId(town.getId() + "");
            dto.setName(town.getIndexName());
            if (ObjectUtils.isNotBlank(haveds) && ObjectUtils.isNotBlank(userid)) {  //d传空的， 说明是点击了 添加的按钮,添加时不需要勾选
                dto.setIsCheck(1);
            }
            townrights.add(dto);
        }
        currentUser.setTownRights(townrights);

        /*
         *市指标
         */
        cityfiler.setPageSize(0);
        cityfiler.setIndexType("二级指标");
        cityfiler.setDateTime(currentYear);
        List<CountryIndicatorsFilter> cityIndexs = cityIndexService.query(cityfiler);
        String cityIndex = currentUser.getCityIndex();
        List<String> citystr = Util.strToList(cityIndex);  //字符串改list
        List<IndexRightDTO> cityRights = new ArrayList<>();
        for (CountryIndicatorsFilter item : cityIndexs) {
            IndexRightDTO dto = new IndexRightDTO();
            dto.setId(item.getId() + "");
            dto.setName(item.getIndexName());
            List<String> cityId = citystr.stream().filter(s -> s.equals(item.getId() + "")).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(cityId) && ObjectUtils.isNotBlank(userid)) {
                dto.setIsCheck(1);
            }
            cityRights.add(dto);
        }

        currentUser.setCityRights(cityRights);

        /*
          县直单位指标
         */
        departFilter.setDateTime(currentYear);
        departFilter.setPageSize(0);
        List<CountryUnitIndicatorsEntity> departIndex = departIndexSercice.query(departFilter);
        String deptstr = currentUser.getDepartIndex();
        List<String> deptArray = Util.strToList(deptstr);
        List<IndexRightDTO> deptRights = new ArrayList<>();
        for (CountryUnitIndicatorsEntity item : departIndex) {
            IndexRightDTO dto = new IndexRightDTO();
            dto.setName(item.getIndexName());
            dto.setId(item.getId() + "");
            List<String> deptId = deptArray.stream().filter(s -> s.equals(item.getId() + "")).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(deptId) && ObjectUtils.isNotBlank(userid)) {
                dto.setIsCheck(1);
            }
            deptRights.add(dto);

        }
        currentUser.setDeptRights(deptRights);
        /**--------------菜单数目-------**/
        String allMenusSr = loginUser.getHaveRight();
        List<String> allMenus = Util.strToList(allMenusSr); //所有菜单
        List<IndexRightDTO> menuslist = new ArrayList<>();
        for (String item : allMenus) {
            MenuLists menus = rolePerService.getMenus(item);
            IndexRightDTO dto = new IndexRightDTO();
            dto.setName(menus.getCodename());
            dto.setId(menus.getCode());
            menuslist.add(dto);
        }

        //用户id没有传过来，不用设置勾选状态
        if (ObjectUtils.isNotBlank(userid)) {
            List<String> checkMenulist = Util.strToList(currentUser.getRoleRight()); //已勾选的菜单
            for (IndexRightDTO item : menuslist) {

                List<String> checkMenus = checkMenulist.stream().filter(s -> s.equals(item.getId())).collect(Collectors.toList());
                if (ObjectUtils.isNotBlank(checkMenus)) {
                    item.setIsCheck(1);
                }
            }
        }

        currentUser.setMenuRights(menuslist);

        if (ObjectUtils.isBlank(userid)) {
            currentUser = new UserFilter();
            currentUser.setMenuRights(menuslist);
            currentUser.setDeptRights(deptRights);
            currentUser.setCityRights(cityRights);
            currentUser.setTownRights(townrights);
        }
        HashMap<String, Object> rights = new HashMap<>();
        rights.put("data", currentUser);
        System.out.println("/getUserinfo");
        return ResultUtils.getSuccessResults(rights);
    }


    //自定义
    @PostMapping("/setManage")
    public Result<HashMap<String, Object>> setManage(@RequestBody SetTimeFilter filter) {

        String optionType = filter.getOptionType();
        String setType = filter.getIndexClass();
        HashMap<String, Object> dataMap = new HashMap<>();
        switch (optionType) {
            case "query":

                SetTimeEntity citytime = setTimeService.findByIndexClass(setType);
                dataMap.put("data", citytime);

                return ResultUtils.getSuccessResults(dataMap);
            case "update":

                SetTimeFilter settimes = new SetTimeFilter();
                settimes.setId(filter.getId());
                settimes.setIndexClass(setType);
                settimes.setStartTime(filter.getStartTime());
                settimes.setEndTime(filter.getEndTime());
                settimes.setIsThisMonth(filter.getIsThisMonth());
                setTimeService.updateTime(settimes);
                break;

        }


        System.out.println("-------接口： /setManage");
        return ResultUtils.getSuccessResults(dataMap);
    }


    //获取县领导下拉框
    @PostMapping("/getManage")
    public Result<HashMap<String, Object>> getLeads(@RequestBody IndexUserDTO filter) {
        UserFilter userFilter = new UserFilter();
        userFilter.setIsLeader(1);
        List<UserFilter> lists = userService.queryUsers(userFilter);
        Map<String, List<UserFilter>> collect = lists.stream().collect(Collectors.groupingBy(UserFilter::getDepartment));

        List<DepartDTO> departlists = new ArrayList<>();

        for (Map.Entry<String, List<UserFilter>> entry : collect.entrySet()) {
            DepartDTO dto = new DepartDTO();
            dto.setDepartAddr(entry.getKey());
            List<UserDTO> userdtos = new ArrayList<>();
            List<UserFilter> value = entry.getValue();
            for (UserFilter item : value) {

                UserDTO user = new UserDTO();
                BeanUtils.copyProperties(item, user);
                userdtos.add(user);
                dto.setDepartcode(user.getDepartcode());
            }
            dto.setUserlists(userdtos);
            departlists.add(dto);


        }
        HashMap<String, Object> leaderdata = new HashMap<>();

        leaderdata.put("data", departlists);

        return ResultUtils.getSuccessResults(leaderdata);

    }


    /**
     * 角色管理增删改
     */
    @PostMapping("/roleManage")
    public Result<HashMap<String, Object>> roleManage(@RequestBody RolePerFilter filter) {

        String tel = filter.getLoginTel();
        UserFilter userInfo = getUserInfo(tel);
        String optionType = filter.getOptionType();
        RolePerEntity record = new RolePerEntity();
        record.setRole(filter.getRole());
        record.setDepartIndex(StringUtils.isBlank(filter.getDepartIndex()) ? null : filter.getDepartIndex().replace(" ", ""));
        record.setCityIndex(StringUtils.isBlank(filter.getCityIndex()) ? null : filter.getCityIndex().replace(" ", ""));
        record.setIndexRight(StringUtils.isBlank(filter.getIndexRight()) ? null : filter.getIndexRight().replace(" ", ""));
        record.setHaveRight(StringUtils.isBlank(filter.getRoleRight()) ? null : filter.getRoleRight().replace(" ", ""));
        record.setBtnRight(StringUtils.isBlank(filter.getBtnRight()) ? null : filter.getBtnRight().replace(" ", ""));
        record.setDepartCode(userInfo.getDepartcode());
        record.setRoleRight(StringUtils.isBlank(filter.getRoleRight()) ? null : filter.getRoleRight().replace(" ", ""));
        record.setHaveRight(StringUtils.isBlank(filter.getRoleRight()) ? null : filter.getRoleRight().replace(" ", ""));
        record.setId(filter.getId());
        switch (optionType) {
            case "add":
                record.setId(null);
                rolePerService.insert(record);


                break;
            case "update":
                rolePerService.updateByPrimaryKeySelective(record);
                break;
            case "del":
                rolePerService.deleteByPrimaryKey(record.getId());
                break;

            case "query":

                RolePerFilter rolePerEntity = new RolePerFilter();

                rolePerEntity.setRole(filter.getRole());

                List<RolePerFilter> query = rolePerService.query(rolePerEntity);

                HashMap<String, Object> map = new HashMap<>();

                List<SystemDTO> sysdtos = new ArrayList<>();

                for (RolePerFilter item : query) {

                    sysdtos.add(new SystemDTO(item.getId(), item.getRole(), "角色管理", "3", item));

                }
                map.put("data", query);
                return ResultUtils.getSuccessResults(map);


        }


        return ResultUtils.getSuccessResults(null);
    }

    /**
     * 获取角色具体权限 信息
     */
    @PostMapping("/getRoleInfo")
    public Result<HashMap<String, Object>> getRoleInfo(@RequestBody RolePerFilter filter) {

        String loginTel = filter.getLoginTel();
        String currentYear = getCurrentYear();
        Long userid = filter.getId();  //id 为空 说明是新增的操作
        UserFilter userInfo = getUserInfo(loginTel);

        List<IndexRightDTO> menuRights = new ArrayList<>();
        List<IndexRightDTO> cityRights = new ArrayList<>();
        List<IndexRightDTO> deptRights = new ArrayList<>();
        List<IndexRightDTO> townRights = new ArrayList<>();

        RolePerFilter role = new RolePerFilter();
        if (ObjectUtils.isNotBlank(userid)) {
            RolePerFilter rolePerEntity = new RolePerFilter();
            rolePerEntity.setId(userid);
            List<RolePerFilter> rolelists = rolePerService.query(rolePerEntity);
            role = rolelists.get(0);

        }


        //市对县指标：
        String cityIndex = role.getCityIndex();
        List<String> citylists = Util.strToList(cityIndex);


        CountryIndicatorsFilter cityfilter = new CountryIndicatorsFilter();
        cityfilter.setPageSize(0);
        cityfilter.setIndexType("二级指标");
        cityfilter.setDateTime(currentYear);
        List<CountryIndicatorsFilter> cityIndexs = cityIndexService.query(cityfilter);
        /*
          设置勾选状态
         */
        for (CountryIndicatorsFilter item : cityIndexs) {

            List<String> collect = citylists.stream().filter(s -> s.equals(item.getId() + "")).collect(Collectors.toList());

            IndexRightDTO dto = new IndexRightDTO();
            dto.setName(item.getIndexName());
            dto.setId(item.getId() + "");

            if (ObjectUtils.isNotBlank(collect) && ObjectUtils.isNotBlank(userid)) {
                dto.setIsCheck(1);
            }
            cityRights.add(dto);

        }
        /*
         *县对乡指标
         */

        TownIndicatorsFilter townfilter = new TownIndicatorsFilter();
        townfilter.setIndexType("二级指标");
        townfilter.setDateTime(currentYear);
        List<TownIndicatorsFilter> listIndexs = townIndicatorsService.query(townfilter);
        String townIndexs = role.getIndexRight();
        List<String> haves = Util.strToList(townIndexs);
        //  List<IndexRightDTO> townrights = new ArrayList<>();
        for (TownIndicatorsFilter town : listIndexs) {
            List<String> haveds = haves.stream().filter(s -> s.equals(town.getId() + "")).collect(Collectors.toList());
            IndexRightDTO dto = new IndexRightDTO();
            dto.setName(town.getIndexName());
            dto.setId(town.getId() + "");

            if (ObjectUtils.isNotBlank(haveds) && ObjectUtils.isNotBlank(userid)) {  //d传空的， 说明是点击了 添加的按钮,添加时不需要勾选
                dto.setIsCheck(1);
            }
            townRights.add(dto);
        }

        /*
             县直单位
         */
        CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
        departFilter.setDateTime(currentYear);
        departFilter.setPageSize(0);
        List<CountryUnitIndicatorsEntity> departIndex = departIndexSercice.query(departFilter);
        String deptstr = role.getDepartIndex();
        List<String> deptArray = Util.strToList(deptstr);
        for (CountryUnitIndicatorsEntity item : departIndex) {
            IndexRightDTO dto = new IndexRightDTO();
            dto.setId(item.getId() + "");
            dto.setName(item.getIndexName());
            List<String> deptId = deptArray.stream().filter(s -> s.equals(item.getId() + "")).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(deptId) && ObjectUtils.isNotBlank(userid)) {
                dto.setIsCheck(1);
            }
            deptRights.add(dto);

        }


        //全部菜单权限；
        String haveRight = userInfo.getHaveRight();
        List<String> menus = Util.strToList(haveRight);
        for (String item : menus) {
            MenuLists menu = rolePerService.getMenus(item);
            IndexRightDTO dto = new IndexRightDTO();
            dto.setId(menu.getCode());
            dto.setName(menu.getCodename());
            menuRights.add(dto);
        }

        String roleRight = role.getRoleRight();
        List<String> strings = Util.strToList(roleRight);

        for (IndexRightDTO item : menuRights) {
            List<String> collect = strings.stream().filter(s -> s.equals(item.getId() + "")).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(collect) && ObjectUtils.isNotBlank(userid)) {
                item.setIsCheck(1);
            }

        }


        role.setDeptRights(deptRights);
        role.setCityRights(cityRights);
        role.setTownRights(townRights);
        role.setMenuRights(menuRights);


        HashMap<String, Object> map = new HashMap<>();
        map.put("data", role);


        return ResultUtils.getSuccessResults(map);
    }


    /**
     * 单位查询主要入口
     *
     * @param filter
     * @return
     */
    @PostMapping("/manageDeptClass")
    public Result deptClassManage(@RequestBody DepartClassFilter filter) {

        String optionType = filter.getOptionType();

        if (StringUtils.isBlank(optionType)) {

            return ResultUtils.getResults("500", "参数错误", null);
        }

        String currentYear = getCurrentYear();
        DepartClass entity = new DepartClass();
        entity.setClassname(filter.getClassname());
        entity.setId(filter.getId());
        String weightlists = filter.getWeightLists();
        List<DepartClassItem> listItem = new ArrayList<>();
        if (StringUtils.isNotBlank(weightlists)) {
            JSONArray array = JSONArray.parseArray(weightlists);
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                DepartClassItem item = obj.toJavaObject(DepartClassItem.class);
                listItem.add(item);
            }

            entity.setWeightList(listItem);
        }
        /*entity.setWeightList(filter.getWeightList());
        HashMap<String, Object> departWeight =  new HashMap<>();*/
        switch (optionType) {

            case "query":
                //departWeight = dpclassService.getDepartWeight(currentYear);
                break;
            case "add":

                String s = dpclassService.saveDepartWeight(entity);
                break;
            case "update":
                // DepartClass entity1 = new DepartClass();
                if (ObjectUtils.isBlank(entity.getId())) {
                    return ResultUtils.getResults("500", "id不能为空", null);
                }
                int weight = itemService.updateOrSaveWeight(entity);
                break;
            case "del":
                if (ObjectUtils.isBlank(entity.getId())) {
                    return ResultUtils.getResults("500", "id不能为空", null);
                }
                DepartClassFilter deleteFilter = new DepartClassFilter();
                deleteFilter.setId(filter.getId());
                String delete = dpclassService.delete(deleteFilter);
                break;

            default:
                return ResultUtils.getResults("500", "参数错误", null);

        }


        return ResultUtils.getSuccessResults(null);
    }


    /**
     * 单位分类详细信息
     *
     * @param filter
     * @return
     */
    @PostMapping("/geClassInfo")
    public Result getClassInfo(@RequestBody DepartClassFilter filter) {

        Long id = filter.getId();
        String currentYear = getCurrentYear();
        HashMap<String, Object> departWeight = dpclassService.getDepartWeight(currentYear);
        Object tableData = departWeight.get("tableData");
        List<Map<String, Object>> dataMap = ((List<Map<String, Object>>) tableData);
        List<Map<String, Object>> filterlist = dataMap.stream().filter(s -> s.get("id").toString().equals(id.toString())).collect(Collectors.toList());


        Map<String, Object> map = filterlist.get(0);

        HashMap<String, Object> data = new HashMap<>(map);
        return ResultUtils.getSuccessResults(data);


    }


    @PostMapping("/boforeAddDeptClass")
    public Result beforeClss() {

        String currentYear = getCurrentYear();
        List<DepartClassHead> heads = headService.queryByDatetime(currentYear);

        List<HashMap<String, Object>> listMap = new ArrayList<>();

        for (DepartClassHead head : heads) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", null);
            map.put("weightName", head.getWeightName());
            map.put("headId", head.getId());
            map.put("weight", 0);
            map.put("classId", null);
            listMap.add(map);
        }

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("weightList", listMap);
        return ResultUtils.getSuccessResults(dataMap);
    }

    /**
     * 查询单位分类 所有考核权重名称
     */
    @PostMapping("/getClasshead")
    public Result<HashMap<String, Object>> getClassHead() {

        String currentYear = getCurrentYear();
        HashMap<String, Object> map = new HashMap<>();
        List<DepartClassHead> heads = headService.queryByDatetime(currentYear);
        map.put("list", heads);
        map.put("datetime", currentYear);
        return ResultUtils.getSuccessResults(map)
                ;

    }

    @PostMapping("/updateClassHead")
    public Result<String> updateClassHead(@RequestBody DepartClassFilter filter) {

        String datetime = filter.getDatetime();

        List<Long> delList = filter.getDelList();//(获取被删除的id)
        String delLists = filter.getDelLists();

        List<String> strings = Util.strToList(delLists);

        for (String aLong : strings) {
            if (aLong.equals("1")
                    || aLong.equals("2") || aLong.equals("3") || aLong.equals("4")
            ) {
                continue;
            }

            headService.delete(new Long(aLong));
        }
        DepartClass entity = new DepartClass();
        //修改或添加的表头；
        List<DepartClassHead> saveList = new ArrayList<>();
        String weightlists = filter.getWeightLists();
        List<DepartClassHead> headList = new ArrayList<>();
        if (StringUtils.isNotBlank(weightlists)) {
            JSONArray array = JSONArray.parseArray(weightlists);
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                DepartClassHead item = obj.toJavaObject(DepartClassHead.class);
                headList.add(item);
            }

        }
        for (DepartClassHead head : headList) {

            if (ObjectUtils.isBlank(head.getId())) {
                head.setDatetime(datetime);
                saveList.add(head);
            } else

                headService.update(head);


        }

        if (saveList.size() > 0) {
            headService.saveItems(saveList);
        }


        return ResultUtils.getResults(Result.Status.SUCCESS, "操作成功");
        //  itemService.updateOrSaveWeight(entity);

    }

    /**
     * 考评机制：
     */
    @RequestMapping("/criteriaManage")
    public Result<HashMap<String, Object>> criteriaManage(@RequestBody CriteriaFilter filter) {
        HashMap<String, Object> map = criteriaService.criteriaManage(filter);
        int code = (int) map.get("code");
        if (200 != code) {
            String msg = (String) map.get("msg");
            return ResultUtils.getResults(Result.Status.ERROR, msg, null);
        }

        return ResultUtils.getSuccessResults(map);
    }


    @PostMapping("/getUnionCode")
    private Result<HashMap<String, Object>> getunionCode()
    {
        List<SysUnionCode> sysUnionCodes = unionService.selectListCode();
        HashMap<String,Object> map  = new HashMap<>();
        map.put("data",sysUnionCodes);
        return ResultUtils.getSuccessResults(map);

    }

}
